﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;

namespace SPOffline.Web
{
    /// <summary>
    /// Timer job which either deploys or retracts the appoffline.htm file.
    /// </summary>
    public class SPOfflineJob : SPJobDefinition
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SPOfflineJob"/> class.
        /// </summary>
        public SPOfflineJob()
        { }

        /// <summary>
        /// Initializes a new instance of the <see cref="SPOfflineJob"/> class.
        /// </summary>
        /// <param name="webApp">The web app.</param>
        public SPOfflineJob(SPWebApplication webApp)
            : base(Constants.JobName, webApp, null, SPJobLockType.None)
        {
            Title = Constants.JobName;
        }

        /// <summary>
        /// Executes the job definition.
        /// </summary>
        /// <param name="targetInstanceId">For target types of <see cref="T:Microsoft.SharePoint.Administration.SPContentDatabase"></see> this is the database ID of the content database being processed by the running job. This value is Guid.Empty for all other target types.</param>
        public override void Execute(Guid targetInstanceId)
        {
            try
            {
                // get the settings
                var settings = SPOfflineSettings.GetSettings(WebApplication);

                // enumerate the iis zone settings
                foreach (var pair in WebApplication.IisSettings)
                {
                    var vDirPath = pair.Value.Path.FullName + @"\app_offline.htm";
                    var templatePath = SPUtility.GetGenericSetupPath(@"TEMPLATE\ADMIN\SPOffline\app_offline.htm");

                    // delete the file if exists
                    if (File.Exists(vDirPath))
                    {
                        File.Delete(vDirPath);
                    }

                    // if the application should be offline, copy the file
                    if (!settings.IsOnline)
                    {
                        // load template
                        var template = File.ReadAllText(templatePath);
                        var content = template.Replace(Constants.TemplateContentToken, settings.OfflineMessage);

                        // save file
                        File.WriteAllText(vDirPath, content);

                    }
                }
            }
            catch(Exception ex)
            {
                //TODO: log   
            }
        }

    }

}
